
from core import AbstractTag, PytmlError
from doctype import Doctype

__all__ = ['Content']

class _ContentLine(AbstractTag):
    def __init__(self, content):
        AbstractTag.__init__(self, '_content_line')

        self.content = content
        self.doBreak = True

    def toString(self, tab, doctype):
        returnString = '\t'*tab + self.content
        endString = ''

        if self.doBreak:
            if doctype and doctype.getType() == 'XHTML':
                endString = '<br />\n'
            else:
                endString += '<br>\n'

        return returnString + endString


class Content(AbstractTag):
    string = 'string'
    code = 'code'
    def __init__(self):
        AbstractTag.__init__(self, 'content')

        self.__contentType = Content.string

    def addTag(self, inTag, inPosition=-1):
        if not isinstance(inTag, _ContentLine):
            raise PytmlError, 'please, don\'t add a tag to Content tags by hand'
        else:
            inTag.setParentTag(self, inPosition)

    def set(self, value):
        if value:
            self.removeAllChildren()
            lines = value.splitlines()
            for line in lines:
                contentLine = _ContentLine(line)
                self.addTag(contentLine, -1)

            self._getChildrenTagsByReference()[-1].doBreak = False

    def get(self):
        retValue = ''
        for child in self.getChildrenTags():
            retValue += child.content
        return retValue

    def setContentType(self, inType):
        self.__contentType = inType

    def getContentType(self):
        return self.__contentType

    def toString(self, tab=0, doctype=Doctype('XHTML', 'Strict')):
        content = ''
        children = self._getChildrenTagsByReference()

        for child in children:
            content += child.toString(tab, doctype)

        return content
